/*
 *
 * System2 Simulation Framework
 * Copyright (C) 2011 - 2012 Jacob Dawid
 * jacob.dawid@googlemail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "packagestreemodel.h"
#include "packagestreeview.h"
#include <QTreeWidgetItem>
#include <QDrag>
#include <QMimeData>
#include <QSortFilterProxyModel>
#include <QPainter>

namespace System2 {
    PackagesTreeView::PackagesTreeView(QWidget *parent) :
        QTreeView(parent) {
        setDragEnabled(true);
        setIconSize(QSize(50, 31));
    }

    void PackagesTreeView::startDrag(Qt::DropActions supportedActions) {
        QDrag *drag = new QDrag(this);
        // TODO: Convert into MIME
        QMimeData *mimeData = new QMimeData();

        QSortFilterProxyModel *sortFilterProxyModel
                = dynamic_cast<QSortFilterProxyModel*>(model());

        QPixmap pixmap(100, 62);

        // Draw a black rectangle in case the following code fails.
        pixmap.fill(QColor(0, 0, 0));

        if(sortFilterProxyModel) {
            PackagesTreeModel* packagesTreeModel
                    = dynamic_cast<PackagesTreeModel*>(sortFilterProxyModel->sourceModel());
            if(packagesTreeModel) {
                QStandardItem *item
                        = packagesTreeModel->itemFromIndex(
                            sortFilterProxyModel->mapToSource(
                                currentIndex()));
                if(item) {
                    QIcon icon(item->icon());
                    pixmap = icon.pixmap(100, 62);

                    mimeData->setData("application/x-s2-component", item->data().toByteArray());
                    drag->setMimeData(mimeData);
                }
            }
        }

        drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
        drag->setPixmap(pixmap);

        drag->exec(supportedActions);
    }
}
